/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "securec.h"
#include "sle_ssap_common_parcel.h"
#include "sle_hilog.h"

namespace OHOS {
namespace NearLink {
namespace SleStandard {
Uuid::Uuid(const SleUuid &uuid)
{
    len_ = uuid.len;
    memcpy_s(uuid_, UUID_LEN, uuid.uuid, uuid.len);
}

bool Uuid::Marshalling(Parcel &parcel) const
{
    if(!parcel.WriteUint8(len_)) {
        return false;
    }
    for (size_t i = 0; i < UUID_LEN; i++) {
        if(!parcel.WriteUint8(uuid_[i])) {
            return false;
        }
    }
    return true;
}

Uuid *Uuid::Unmarshalling(Parcel &parcel)
{
    Uuid *uuid = new Uuid();
    if (uuid != nullptr && !uuid->ReadFromParcel(parcel)) {
        delete uuid;
        uuid = nullptr;
    }
    return uuid;
}

bool Uuid::ReadFromParcel(Parcel &parcel)
{
    if (!parcel.ReadUint8(len_)) {
        return false;
    }
    for (size_t i = 0; i < UUID_LEN; i++) {
        if (!parcel.ReadUint8(uuid_[i])) {
            return false;
        }
    }
    return true;
}

SleUuid Uuid::ConvertToSleUuid() const
{
    SleUuid uuid;
    uuid.len = len_;
    for (size_t i = 0; i < UUID_LEN; i++) {
        uuid.uuid[i] = uuid_[i];
    }
    return uuid;
}

SleErrorCode Uuid::CheckSleUuid(const SleUuid &uuid)
{
    if (uuid.len == 0) {
        return SLE_NO_ERROR;
    }
    bool AllZero = true;
    bool AllFF = true;
    for (int i = 0; i < UUID_LEN; ++i) {
        if (uuid.uuid[i] != 0x00) {
            AllZero = false;
        }
        if (uuid.uuid[i] != 0xFF) {
            AllFF = false;
        }
    }
    SLE_LOGD("check sle uuid result:%d %d", AllZero, AllFF);
    SLE_LOGD("check sle uuid result:%d", (!AllZero && !AllFF));
    SLE_ASSERT_AND_RETURN_RET_LOG((!AllZero && !AllFF), SLE_ERR_INVALID_PARAM, "check uuid error!");
    return SLE_NO_ERROR;
}
} // SleStandard
} // NearLink
} // OHOS